package com.zmm.util.time;

import com.zmm.common.enums.DatePatternEnums;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 日期线程类
 * @author 900045
 * @description:
 * @name ThreadDateUtil
 * @date By 2021-06-22 11:35:15
 */
public final class ThreadDateUtil {
	
	/**
	 *  格式化 线程集
	 */
	private static Map<String, ThreadLocal<DateFormat>> threadLocalMap  = new HashMap<>();

	/**
	 *    获取日期格式化工具对象
	 *    线程安全
	 * @return
	 */
	public static DateFormat getDateFormat() {
		return getDateFormat(DatePatternEnums.YYYY_MM_DD_HH_MM_SS.pattern);
	}

	/**
	 *  获取日期格式化工具对象
	 *      线程安全
	 * @param format    格式      可取些工具类中的常量格式，默认为yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static DateFormat getDateFormat(String format) {
		ThreadLocal<DateFormat> threadLocal = threadLocalMap.get(format);
		DateFormat df = null;
		if (threadLocal == null) {
			threadLocal = new ThreadLocal<DateFormat>();
			df = new SimpleDateFormat(format);
			threadLocal.set(df);
			threadLocalMap.put(format, threadLocal);
		} else {
			df = threadLocal.get();
			if (df == null) {
				df = new SimpleDateFormat(format);
				threadLocal.set(df);
				threadLocalMap.put(format, threadLocal);
			}
		}
		return df;
	}

	public static String formatDate(Date date) throws ParseException {
		return getDateFormat().format(date);
	}

	public static Date parse(String strDate) throws ParseException {
		return getDateFormat().parse(strDate);
	}
}
